from flask import Blueprint, render_template, request, jsonify
from app.models import db, ExecutionRecord, ExecutionStepRecord, Scene, Environment
from datetime import datetime

# 创建蓝图
record_bp = Blueprint('record', __name__, url_prefix='/record')

@record_bp.route('/')
def list_records():
    """执行记录列表页面"""
    return render_template('record/index.html')

@record_bp.route('/data')
def get_records():
    """获取执行记录列表数据"""
    # 获取查询参数
    search = request.args.get('search', '')
    filter_status = request.args.get('filter', 'all')
    page = int(request.args.get('page', 1))
    per_page = int(request.args.get('per_page', 10))
    
    # 构建查询
    query = ExecutionRecord.query
    
    # 状态过滤
    if filter_status != 'all':
        query = query.filter(ExecutionRecord.status == filter_status)
    
    # 搜索过滤
    if search:
        query = query.join(Scene).filter(
            (Scene.name.ilike(f'%{search}%'))
        )
    
    # 分页
    pagination = query.order_by(ExecutionRecord.start_time.desc()).paginate(page=page, per_page=per_page)
    
    # 构建响应数据
    records = [record.to_dict() for record in pagination.items]
    
    return jsonify({
        'records': records,
        'pagination': {
            'current_page': pagination.page,
            'per_page': pagination.per_page,
            'total_items': pagination.total,
            'total_pages': pagination.pages
        }
    })

@record_bp.route('/<int:record_id>', methods=['GET'])
def get_record(record_id):
    """获取执行记录详情"""
    record = ExecutionRecord.query.get_or_404(record_id)
    
    # 获取步骤记录
    steps = []
    for step in record.steps:
        if step.parent_id is None:  # 只获取顶级步骤
            steps.append(step.to_dict())
    
    return jsonify({
        'success': True,
        'record': record.to_dict(),
        'steps': steps
    })

@record_bp.route('/<int:record_id>/rerun', methods=['POST'])
def rerun_record(record_id):
    """重新执行记录"""
    old_record = ExecutionRecord.query.get_or_404(record_id)
    
    # 创建新的执行记录
    new_record = ExecutionRecord(
        scene_id=old_record.scene_id,
        environment_id=old_record.environment_id,
        status='running',
        trigger='manual',
        start_time=datetime.now(),
        variables={}
    )
    
    db.session.add(new_record)
    db.session.commit()
    
    # 在实际应用中，这里应该触发异步任务来执行场景
    # 为了演示，我们直接返回成功
    
    return jsonify({
        'success': True,
        'message': '已开始重新执行',
        'record_id': new_record.id
    })